import {
	ref,
	watch,
	toRaw
} from 'vue'

export const useRemainTimeFormat = (data) => {
	const formatTime = ref('')
	const timer = ref(null)
	const formatDatetime = (time) => {
		clearInterval(timer.value)
		let res = 0
		const showTime = () => {
			if (time < 0) {
				clearInterval(timer.value)
				//TODO:可以加上计时终止时的处理方法
			}
			res = changeDateTime(time)
			return res
		}
		timer.value = setInterval(() => {
			time -= 1000
			res = showTime()
			formatTime.value = res
			console.log('res', res);
		}, 1000)

	}

	const changeDateTime = (time) => {
		const h = padWidthZero((Math.floor(time / 1000 / 60 / 60) % 24))
		const m = padWidthZero((Math.floor(time / 1000 / 60 % 60)))
		const s = padWidthZero((Math.floor(time / 1000 % 60)))
		return h + '时' + m + '分' + s + '秒'
	}

	const padWidthZero = (data) => {
		return data < 10 ? '0' + data : data
	}

	const init = (value) => {
		formatTime.value = formatDatetime(value._exp_time)
	}

	watch(data, (value) => {
		console.log('value', value);
		if (value) {
			init(toRaw(value))
		}
	}, {
		immediate: true
	})


	const clearTimeCount = () => {
		clearInterval(timer.value)
	}

	return {
		formatTime,
		clearTimeCount
	}
}